//
//  DetailedViewController.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 3/14/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DetailedViewController.h"

//Description: this view controller is only concerned with CCR Objects at this point and not concerned
// with whether it came from Google Health or from a hospital web service.
@implementation DetailedViewController
@synthesize ccrObjects;
@synthesize ccrSubSection, googlehealth;
@synthesize LoggedInThruGoogleHealth, UserSelectedDecryption, ptrToCPabe;
@synthesize selTarget, selFunction, basesheet, progbar;

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
	self.UserSelectedDecryption = NO;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	// if(LoggedInThruGoogleHealth == NO) {
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Options" style:UIBarButtonItemStylePlain 
																				  target:selTarget action:selFunction] autorelease];
	
	lockIcon = [UIImage imageNamed:@"Lock-64.png"];
	ccrIcon = [UIImage imageNamed:@"Record-64.png"];
	/*}
	else {
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Decrypt" style:UIBarButtonItemStylePlain 
																				target:self action:@selector(ccrOptions)] autorelease];
	}*/
}

- (void)viewWillAppear:(BOOL)animated {	
	NSLog(@"Reloading...?");
	[self.tableView reloadData];
    [super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [ccrObjects count];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row = [indexPath row];
	/* check if the entry is encrypted: if YES return nil otherwise indexPath */
	CCRObject *c = [ccrObjects objectAtIndex:row];
	if([c.item isEqualToString:ENCRYPTED_ENTRY]) {
		return nil;
	}
	
	return indexPath;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // Set up the cell...[Ignore the confusion of cell names, was trying to avoid creating another cell identifier!]
	NSUInteger row = [indexPath row];
	CCRObject *c = [ccrObjects objectAtIndex:row];
	if([c.item isEqualToString:ENCRYPTED_ENTRY]) {
		static NSString *EncryptedCellIdentifier = @"EncryptedCellIdentifier";
		
		EncryptedCell *cell1 = (EncryptedCell *)[tableView dequeueReusableCellWithIdentifier:EncryptedCellIdentifier];
		if (cell1 == nil) {
			// load nib life
			NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EncryptedCell" 
														 owner:self 
													   options:nil];
			// retrieve cell object in nib file.
			cell1 = [nib objectAtIndex:0];
		}
		
		cell1.imageView.image = lockIcon;
		cell1.entry_title.text = ENCRYPTED_CELL;
		cell1.myIndex = row;
		cell1.myTarget = self;
		cell1.theFunction = @selector(decryptSpecifiedEntry:);
		
		return cell1;
    }

	static NSString *ProfileCellIdentifier = @"ProfileCellIdentifier";
    
	ProfileCell *cell = (ProfileCell *)[tableView dequeueReusableCellWithIdentifier:ProfileCellIdentifier];
	if (cell == nil) {
			//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			// load nib life
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProfileCell" 
													 owner:self 
												   options:nil];
			// retrieve cell object in nib file.
		cell = [nib objectAtIndex:0];
	}
		
	NSDateFormatter *dFormat = [[NSDateFormatter alloc] init];
	[dFormat setDateFormat:@"MM/dd/yy"];
	cell.section.text = c.item;
	cell.item.text = c.description;
	cell.date.text = [dFormat stringFromDate:c.editDate];
	cell.imageView.image = ccrIcon;
	[dFormat release];
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSUInteger row = [indexPath row];
	CCRObject *c = [ccrObjects objectAtIndex:row];
	NSLog(@"Viewing '%@' record.", c.item);
	if([c isEntryEncrypted] == YES) {
		// see if user has already attempted a decryption. If so, we can decrypt here and continue?
		/* TODO: decrypt here */
		
		// send alert to user, it cant be displayed.
#ifdef LOG_DEBUG		
		NSLog(@"Entry contains encrypted data!");
		// still encrypted here ofcourse...
		NSLog(@"decrypt first => '%@'", [c getPlainText]);
#endif
		if(UserSelectedDecryption && LoggedInThruGoogleHealth) {
			/* decrypt through Google Interface? */
			if([c decryptElementFromGoogleHealth:ptrToCPabe] == YES) {
				NSLog(@"Google Health: Decryption in background done.");
				NSString *text = [DetailedViewController parseDescription:c ofCCR:ccrSubSection];
				c.item = text;
				c.editDate = [NSDate date];
			}
		}
		else if(UserSelectedDecryption && !LoggedInThruGoogleHealth) {
			/* through other interfaces */
			if([c decrypt:ptrToCPabe] == YES) {
				NSLog(@"Other interface: decryption in background done.");
				NSString *text = [DetailedViewController parseDescription:c ofCCR:ccrSubSection];
				c.item = text;
				c.editDate = [NSDate date];				
			}
		}
		else {
			UIAlertView *status = [[UIAlertView alloc] initWithTitle:@"Error"
															 message:@"Entry contains encrypted data! Decrypt first."
															delegate:self cancelButtonTitle:nil 
												   otherButtonTitles:@"OK", nil];
			[status show];
			[status release];				
			return;
		}
	}
	
	if(mvc == nil) {
		mvc = [[MedsViewController alloc] initWithNibName:@"MedsViewController" bundle:nil];
	}	
	mvc.title = @"Record";
	mvc.curCategory = [c.ccrsection lowercaseString];
	NSLog(@"Current CCR category: %@", mvc.curCategory);
	NSLog(@"Current CCR xml element: %@", [c getPlainText]);
	[mvc writeToWeb:[c getPlainText]];
	[self.navigationController pushViewController:mvc animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
	[ptrToCPabe CleanUp];
	[ptrToCPabe release];
	[ccrObjects release];
	[ccrSubSection release];
	[googlehealth release];
	[mvc release];
	[basesheet release];
    [super dealloc];
}

#pragma mark -
#pragma mark CCR Options

-(void) decryptSpecifiedEntry:(NSUInteger) index
{
	[self showTheProgress:@"Decrypting entry..."];
	CCRObject *c = [ccrObjects objectAtIndex:index];
	// send alert to user, it cant be displayed.
//#ifdef LOG_DEBUG		
	NSLog(@"Entry contains encrypted data!");
	// still encrypted here ofcourse...
	// NSLog(@"decrypt first => '%@'", [c getPlainText]);
//#endif
	if(LoggedInThruGoogleHealth) {
		/* decrypt through Google Interface? */
		if([c decryptElementFromGoogleHealth:ptrToCPabe] == YES) {
			NSLog(@"Google Health: Decryption in background done.");
			NSString *text = [DetailedViewController parseDescription:c ofCCR:ccrSubSection];
			c.item = text;
			c.editDate = [NSDate date];
		}
		else {
			[basesheet dismissWithClickedButtonIndex:0 animated:YES];
			[self showStatus:@"You do not possess attributes to decrypt entry."];
		}		
	}
	else if(!LoggedInThruGoogleHealth) {
		/* through other interfaces */
		if([c decrypt:ptrToCPabe] == YES) {
			NSLog(@"Other interface: decryption in background done.");
			NSString *text = [DetailedViewController parseDescription:c ofCCR:ccrSubSection];
			c.item = text;
			c.editDate = [NSDate date];				
		}
		else {
			[basesheet dismissWithClickedButtonIndex:0 animated:YES];
			[self showStatus:@"You do not possess appropriate key to decrypt entry."];
		}
	}
	[self.tableView reloadData];
}

-(void) viewABEpolicy:(NSUInteger) index
{
	CCRObject *c = [ccrObjects objectAtIndex:index];
	NSString *message;
	
	message = [c getABEPolicy:ptrToCPabe with:LoggedInThruGoogleHealth];

	UIAlertView *status = [[UIAlertView alloc] initWithTitle:@"Policy" message:message
													delegate:self cancelButtonTitle:nil 
										   otherButtonTitles:@"OK", nil];
	[status show];
	[status release];	
}

	// GDataServiceGoogleHealth *service = [googlehealth healthService]; 
	/*GDataContinuityOfCareRecord *ccr = [XMLParser createCCRDocument:nil];
	SEL callback = @selector(postTicket:finishedWithEntry:error:);

	NSLog(@"Perform upload to Google Health?");
	[googlehealth sendUpdate:ccr withDelegate:self andCallback:callback];
	 */
	/* Support decryption (IMPLEMENT NEXT), upload to GH (DONE), and edit policy (FUTURE WORK) */	

- (void) postTicket:(GDataServiceTicket *)ticket
         finishedWithEntry:(GDataEntryHealthProfile *)feed
                    error:(NSError *)error {
	NSString *message;
	NSString *mytitle = @"Upload";
	if(error == nil) {
		message = @"Successfully uploaded entries!";
		[googlehealth sendNotice:@"Uploading encrypted entry." withContent:@"Successfully uploaded some stuff to your profile!"];
		return;
	}
	else {
		message = @"Failed to upload entries!";
	}
	UIAlertView *status = [[UIAlertView alloc] initWithTitle:mytitle message:message
												  delegate:self cancelButtonTitle:nil 
										 otherButtonTitles:@"OK", nil];
	[status show];
	[status release];	
}

+(NSString *) parseDescription:(CCRObject *) object ofCCR:(NSString *) section
{
	NSString *text = nil;
	NSEnumerator *eN;
	NSXMLElement *xml = [object getPlainText];
	NSLog(@"parse Description => %@", xml);
	
	NSArray *n = [xml elementsForName:@"Body"];
	NSXMLNode *e = [n objectAtIndex:0];	
	NSArray *desc;
	if([section isEqualToString:@"MEDICATION"] ||
	   [section isEqualToString:@"IMMUNIZATION"]) {
		desc = [XMLParser findChild:e withTag:@"ProductName"];
	}
	else if([section isEqualToString:@"PAYER"]) {
		desc = [XMLParser findChild:e withTag:@"Type"];
	}
	else {
		desc = [XMLParser findChild:e withTag:@"Description"];
	}
	
	if([section isEqualToString:@"ALLERGY"])
		eN = [[[desc objectAtIndex:1] children] objectEnumerator];		
	else
		eN = [[[desc objectAtIndex:0] children] objectEnumerator];
	
	NSXMLNode *tmp;
	while(tmp = [eN nextObject]) {
		if([[tmp name] isEqualToString:@"Text"]) {
			NSLog(@"Text => %@", [tmp stringValue]);
			text = [tmp stringValue];
		}
	}
	
	[desc release];
	//	[xmlParser release];
	return text;
}

-(void) actionSheet:(UIActionSheet *) actionSheet clickedButtonAtIndex:(NSInteger) buttonIndex
{
	NSLog(@"DetailedView actionSheet...");
	[actionSheet release];
}

-(void) incrementBar:(id) timer
{
	amountDone += 5.0f;
	CGFloat prog = (amountDone / 20.0);
	// printf("DEBUG progress: '%5.2f'\n", prog);
	[progbar setProgress:prog];
	if(amountDone > 20.0) {
		[basesheet dismissWithClickedButtonIndex:0 animated:YES];
		[timer invalidate];
	}
}

-(void) showStatus:(NSString *) message
{
	UIAlertView *status = [[UIAlertView alloc] initWithTitle:@"Status" message:message
													delegate:self cancelButtonTitle:nil 
										   otherButtonTitles:@"OK", nil];
	[status show];
	[status release];	
}

/* Note: consider making the selector passed to NSTimer an function argument so
   that DetailedView is more flexible and natural. 
 */
-(void) showTheProgress:(NSString *) message target:(id) theTarget withInc:(SEL) incrementFunction
{
	if(basesheet == nil) {
		basesheet = [[UIActionSheet alloc] initWithTitle:@"Please Wait" 
												delegate:self 
									   cancelButtonTitle:nil 
								  destructiveButtonTitle:nil 
									   otherButtonTitles:nil];
		[basesheet setNumberOfRows:5];
		[basesheet setMessage:message];		
		
		progbar = [[UIProgressView alloc] initWithFrame:CGRectMake(50.0f, 70.0f, 220.0f, 90.0f)];
		[progbar setProgressViewStyle:UIProgressViewStyleDefault];
		[basesheet addSubview:progbar];
		[progbar release];
	}
	
	// Create the demonstration updates
	[progbar setProgress:(amountDone = 0.0f)];
	// [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(incrementBar:) userInfo:nil repeats:YES];
	[NSTimer scheduledTimerWithTimeInterval:0.5 target:theTarget selector:incrementFunction userInfo:nil repeats:YES];
	[basesheet showInView:self.view];	
}

-(void) showTheProgress:(NSString *) message
{
	if(basesheet == nil) {
		basesheet = [[UIActionSheet alloc] initWithTitle:@"Please Wait" 
												delegate:self 
									   cancelButtonTitle:nil 
								  destructiveButtonTitle:nil 
									   otherButtonTitles:nil];
		[basesheet setNumberOfRows:5];
		[basesheet setMessage:message];		
		
		progbar = [[UIProgressView alloc] initWithFrame:CGRectMake(50.0f, 70.0f, 220.0f, 90.0f)];
		[progbar setProgressViewStyle:UIProgressViewStyleDefault];
		[basesheet addSubview:progbar];
		[progbar release];
	}
	
	// Create the demonstration updates
	[progbar setProgress:(amountDone = 0.0f)];
	[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(incrementBar:) userInfo:nil repeats:YES];
	[basesheet showInView:self.view];	
}


@end

